package cn.cdzdjd.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Connection.Response;

import cn.cdzdjd.exception.RenException;


public class VendorVideoUtil {
	private static final String baseUrl = "http://47.99.158.118/video-crack/v2/parse?content=";

	public static String getVideoUrl(String url) {
		Response videoRes = JsoupUtil.getUrlResponse(baseUrl + url);
		String videoStr = videoRes.body();
		JSONObject videoJson = new JSONObject(videoStr);
		String videoUrl = videoJson.getJSONObject("data").getString("url");
		return videoUrl;
	}

	public static List<String> getImageUrl(String url) {
		Response videoRes = JsoupUtil.getUrlResponse(baseUrl + url);
		String videoStr = videoRes.body();
		JSONObject videoJson = new JSONObject(videoStr);
		JSONArray imageUrls = videoJson.getJSONObject("data").getJSONArray("imageUrl");
		List<String> posterList = new ArrayList<>();
		for (int i = 0; i < imageUrls.length(); i++) {
			posterList.add(imageUrls.getString(i));
		}
		return posterList;
	}

	public static Map<String, List<String>> getImageAndVideoUrl(String url) {
		Response videoRes = JsoupUtil.getUrlResponse(baseUrl + url);
		String videoStr = videoRes.body();
		JSONObject videoJson = new JSONObject(videoStr);
		if(videoJson.getInt("code")==-2) {
			throw new RenException("作品已被删除");
		}
		JSONObject data = videoJson.getJSONObject("data");
		Map<String, List<String>> map = new HashMap<>();
		if (data.isNull("imageUrl")) {
			String videoUrl = data.getString("url");
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			map.put("videoList", videoList);
			return map;
		} else {
			JSONArray imageUrls = data.getJSONArray("imageUrl");
			List<String> posterList = new ArrayList<>();
			for (int i = 0; i < imageUrls.length(); i++) {
				posterList.add(UrlUtil.setHttps(imageUrls.getString(i)));
			}
			map.put("posterList", posterList);
			return map;
		}
	}
}
